package com.by.zhdoctor.huanxin.util;

import io.swagger.client.ApiException;
import io.swagger.client.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by succy on 17-9-3.
 */

@Component
public class ResponseHandler {
    private static final Logger log = LoggerFactory.getLogger(ResponseHandler.class);
    public ApiResponse<?> handle(HuanXinAPI huanXinAPI) {
        ApiResponse<?> result = null;
        try {
            return huanXinAPI.invokeApi();
        } catch (ApiException e) {
            // 401 token过期
            if (e.getCode() == 401) {
                log.warn("[警告] 当前token不可用，重新生成token并再次调用该api");
                TokenUtil.initToken();
                try {
                    result = huanXinAPI.invokeApi();
                } catch (ApiException e1) {
                    log.error("[异常] 调用环信api时发生异常; msg: {}", e1.getMessage());
                }
                return result;
            }
            // 429  请求过于频繁
            if (e.getCode() == 429) {
                log.warn("[警告] api调用过于频繁");
            }

            // 50X
            if (e.getCode() >= 500) {
                log.info("[信息] 服务器连接失败，正在重连服务器……");
                result = retry(huanXinAPI);
                if (result != null) {
                    return result;
                }
                log.error("[错误] 服务器可能出现故障，请稍后重试");
            }
            result = new ApiResponse<>(e.getCode(), null, null);
            return result;
        }
    }

    /**
     * 重试，当发生50x服务器端错误时，重试3次
     *
     * @param huanXinAPI
     * @return
     */
    public ApiResponse<?> retry(HuanXinAPI huanXinAPI) {
        ApiResponse<?> result = null;
        long time = 5;
        for (int i = 0; i < 3; i++) {
            try {
                TimeUnit.SECONDS.sleep(time);
                log.info("[重试] 第{}次重试……", i);
                result = huanXinAPI.invokeApi();
                if (result != null) {
                    return result;
                }
            } catch (ApiException e1) {
                time *= 3;
            } catch (InterruptedException e1) {
                log.error("[异常] 发生中断异常; msg: {}", e1.getMessage());
            }
        }
        return result;
    }
}
